package cn.com.fuhuitong.wxapi

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import cn.com.fuhuitong.app.WX_APP_ID
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.entity.PayResult
import cn.com.fuhuitong.main.order.ui.activity.OrderPayWaitActivity
import com.blankj.utilcode.util.LogUtils
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.modelpay.PayResp
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import org.greenrobot.eventbus.EventBus

class WXPayEntryActivity : Activity(), IWXAPIEventHandler {

    private lateinit var api: IWXAPI

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID)
        api.handleIntent(intent, this)
    }

    override fun onResp(resp: BaseResp?) {
        this.finish()
        if (resp?.type != ConstantsAPI.COMMAND_PAY_BY_WX) { //  微信支付
            return
        }
        (resp as? PayResp)?.let {
            payByWX(it)
        }
    }

    override fun onReq(req: BaseReq?) = Unit

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        api.handleIntent(intent, this)
    }

    /**
     * 微信支付
     * */
    private fun payByWX(resp: PayResp) {
        val payResult: PayResult = when (resp.errCode) {
            BaseResp.ErrCode.ERR_OK -> PayResult.SUCCESS
            BaseResp.ErrCode.ERR_USER_CANCEL -> PayResult.CANCEL
            else -> PayResult.FAILURE
        }
        EventBus.getDefault().post(
            MainBean(type = payResult, data = null)
        )
    }
}